package com.myx.typhoon.web.bussiness.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.myx.typhoon.common.util.FileUtil;

/**  
 * @author myx
 * @createTime 2016年1月13日 下午2:20:10  
 * 
 */
@Controller
@RequestMapping("/picture")
public class PictureController {
	
	private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

	private static String path_segment = "/upload";
	
	@RequestMapping("/uploadImg") 
	public @ResponseBody String uploadImg(
			@RequestParam(value = "filedata") MultipartFile imgFile,
			HttpServletRequest request) {
		String realPath = request.getSession().getServletContext().getRealPath(path_segment);
		String url = "";
		String err = "";
		if(imgFile != null && !imgFile.isEmpty()) {
			String fileName = imgFile.getOriginalFilename();
			if(FileUtil.checkFileType(fileName)) {
				String randomPath = FileUtil.randomPath();
				String randomFileName = FileUtil.generateRandonFileName(fileName);
				try {
					File saveFile = new File(realPath + randomPath,randomFileName);
					if(!saveFile.exists()) {
						saveFile.mkdirs();
					}
					imgFile.transferTo(saveFile);
				} catch (Exception e) {
					logger.error("uploadImg error",e);
					err = e.getMessage();
				}
				randomPath = randomPath.replace("\\", "/");
				url = request.getHeader("Origin")+request.getContextPath() + path_segment + randomPath + randomFileName;
			}else {
				err = "上传文件格式不符合要求！";
			}
		}else {
			err = "上传文件不能为空！";
		}
		return "{\"err\":\"" + err + "\",\"msg\":\"" + url + "\"}";
	}
}
